########################################################################
#  Searx-Qt - Lightweight desktop application for Searx.
#  Copyright (C) 2020-2022  CYBERDEViL
#
#  This file is part of Searx-Qt.
#
#  Searx-Qt is free software: you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation, either version 3 of the License, or
#  (at your option) any later version.
#
#  Searx-Qt is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with this program.  If not, see <https://www.gnu.org/licenses/>.
#
########################################################################


from searxqt.translations import _


KiB = 1024
MiB = KiB ** 2
GiB = KiB ** 3
TiB = KiB ** 4


def boolToStr(state):
    return _("Yes") if state else _("No")


def listToStr(list_):
    return ", ".join(list_)


def formatFileSize(fileSize):
    """
    @param fileSize: File size in bytes to format to string.
    @type fileSize: uint
    """
    sizeStr = ""

    if fileSize > TiB:  # TiB
        sizeStr = f"{fileSize / TiB:.2f} TB"
    elif fileSize > GiB:  # GiB
        sizeStr = f"{fileSize / GiB:.2f} GB"
    elif fileSize > MiB:  # MiB
        sizeStr = f"{fileSize / MiB:.2f} MB"
    elif fileSize > KiB:  # KiB
        sizeStr = f"{fileSize / KiB:.2f} KB"
    else:
        sizeStr = f"{fileSize} Bytes"
    return sizeStr


## Parse HTML into json
def parseFilesize(filesizeStr):
    if " " not in filesizeStr:
        return 0

    no, unit = filesizeStr.split(" ", 1)

    try:
        no = float(no)
    except ValueError:
        return 0

    if unit == "KiB":
        return int(no * KiB)

    if unit == "MiB":
        return int(no * MiB)

    if unit == "GiB":
        return int(no * GiB)

    if unit == "TiB":
        return int(no * TiB)

    return 0


def formatFileCount(fileCount):
    """
    @param fileCount: File count to format to string.
    @type fileCount: uint
    """
    if fileCount == 1:
        return "1 " + _("file")
    return f"{fileCount} {_('files')}"
